<template>
  <div id="app">
    <el-container class="order-container">
      <el-main>
        <div class="main-content" v-if="!ShowPaymentPage">
          <div class="order-details">
            <el-button
              type="primary"
              size="small"
              @click="goToHome"
              style="float: right; margin-top: -5px"
            >
              返回首页
            </el-button>
          </div>
          <div class="left-column">
            <!-- 收货地址部分 -->
            <el-card class="section-card">
              <template #header>
                <div class="card-header">
                  <span style="font-weight: 600">收货地址</span>
                </div>
              </template>
              <div class="card-body address-info">
                <div class="address-list">
                  <div
                    v-for="(address, index) in addresses"
                    :key="index"
                    class="address-item"
                    :class="{ active: selectedAddress === index }"
                    @click="selectAddress(index)"
                  >
                    <div class="address-icon">
                      <i
                        :class="
                          selectedAddress === index ? 'el-icon-check' : 'el-icon-location'
                        "
                      ></i>
                    </div>
                    <div class="address-content">
                      <div class="address-text">
                        {{ address.province }}{{ address.city }}{{ address.district
                        }}{{ address.detailAddress }}
                      </div>
                      <div class="contact-info">
                        <span>{{ address.receiverName }}</span>
                        <span>{{ address.receiverPhone }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <el-button
                  type="text"
                  @click="showAllAddresses = !showAllAddresses"
                  class="toggle-address-btn"
                >
                  {{ showAllAddresses ? "收起地址" : "显示全部地址" }}
                </el-button>
              </div>
            </el-card>

            <!-- 订单详情部分 -->
            <el-card class="section-card">
              <template #header>
                <div class="card-header">
                  <span style="font-weight: 600">订单信息</span>
                </div>
              </template>
              <div class="card-body order-info">
                <div class="product-details">
                  <div class="product-image">
                    <img :src="product.homeImage" alt="商品图片" />
                  </div>
                  <div class="product-info">
                    <div class="product-name">{{ product.title }}</div>
                    <div class="product-price">¥{{ product.price }}</div>
                    <div class="product-description">
                      商品描述：{{ product.description }}
                    </div>
                  </div>
                </div>

                <!-- 购买数量 -->
                <div class="quantity-selection">
                  <div class="section-title">购买数量</div>
                  <div class="quantity-control">
                    <el-button
                      class="quantity-btn"
                      :disabled="quantity <= 1"
                      @click="decreaseQuantity"
                    >
                      -
                    </el-button>
                    <span class="quantity">{{ quantity }}</span>
                    <el-button class="quantity-btn" @click="increaseQuantity">
                      +
                    </el-button>
                  </div>
                </div>
                <div>
                  <span
                    >留言：<el-input
                      type="textarea"
                      rows="2"
                      placeholder="请输入留言内容"
                      v-model="message"
                    ></el-input
                  ></span>
                </div>
              </div>
            </el-card>
          </div>

          <div class="right-column">
            <!-- 价格明细部分 -->
            <el-card class="section-card">
              <template #header>
                <div class="card-header">
                  <span style="font-weight: 600">价格明细</span>
                </div>
              </template>
              <div class="card-body">
                <div class="price-row">
                  <span>商品总价 共{{ quantity }}件宝贝</span>
                </div>
                <div class="price-row">
                  <span>运费</span>
                  <span>¥0.00</span>
                </div>
                <div class="price-row total-row">
                  <span>合计：</span>
                  <span class="total-price">¥{{ total }}</span>
                </div>

                <el-button
                  @click="confirmPurchase"
                  type="danger"
                  style="width: 100%; margin-top: 20px; padding: 12px"
                >
                  确认购买
                </el-button>
              </div>
            </el-card>
          </div>
        </div>
        <PaymentPageView
          v-if="ShowPaymentPage"
          v-bind:request-dto="requestDto"
          @go-to-order-details="goToOrderDetails"
        ></PaymentPageView>

      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, defineProps } from "vue";
import install from "@/utils/request";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import PaymentPageView from "../order/PaymentPageView.vue";

// 地址信息
const addresses = ref([]);
const selectedAddress = ref(0);
const showAllAddresses = ref(false);
const router = useRouter();
const message = ref("");
const ShowPaymentPage = ref(false);
const requestDto = ref({
 addressId: null,
  productOrderStatus: null,
  productOrderTotalPrice: null,
  productOrderItemPrice: null,
  productId: null,
  sellerId: null,
  productOrderItemNumber: null,
  productOrderUserMessage: ""

});
const selectAddress = (index) => {
  selectedAddress.value = index;
  ElMessage.info(`已选择地址：${addresses.value[index].id}`);
};

const goToHome = () => {
  // router.push('/');
  // 使用 replace 方法替换当前历史记录，防止用户返回到订单详情页
  router.replace("/");
  // 刷新页面
  window.location.reload();
};

const goToOrderDetails = () => {
  ShowPaymentPage.value = false;
};

const props = defineProps({
  productId: {
    type: String,
    required: true,
  },
});

// 商品信息
const product = ref({
  title: "",
  price: null,
  homeImage: "",
  userId: "",
  description: "",
  condition: "",
});
//获取登录用户的所有地址
const getAddress = async () => {
  const res = await install.get("/address/list");
  if (res.data.code === 200) {
    addresses.value = res.data.data;
  } else {
    ElMessage.error(res.data.msg);
  }
};
// 获取商品信息
const getProduct = async () => {
  const res = await install.get(`/platform/get?id=${props.productId}`);

  if (res.data.code === 200) {
    product.value = res.data.data;
  } else {
    ElMessage.error(res.data.msg);
    return;
  }
};

// 数量控制
const quantity = ref(0);

const increaseQuantity = () => {
  if (quantity.value >= product.value.number) {
    ElMessage.warning("已达到库存上限");
    return;
  }

  quantity.value++;
};

const decreaseQuantity = () => {
  if (quantity.value > 1) quantity.value--;
};

// 总价计算
const total = computed(() => {
  return (product.value.price * quantity.value).toFixed(2);
});
const confirmPurchase = async () => {
  if (selectedAddress.value === null) {
    ElMessage.warning("请选择收货地址");
    return;
  }
  if (quantity.value < 1) {
    ElMessage.warning("购买数量不能少于1");
    return;
  }
   requestDto.value = {
    addressId: addresses.value[selectedAddress.value].id,
    productOrderStatus: 0,
    productOrderTotalPrice: Number(total.value),
    productOrderItemPrice: Number(product.value.price),
    productId: props.productId,
    productOrderItemNumber: quantity.value,
    productOrderUserMessage: message.value,
    sellerId: product.value.userId
  };
  ShowPaymentPage.value = true;

};

onMounted(() => {
  getAddress();
  getProduct();
});
</script>

<style scoped>
body {
  background-color: #f5f7fa;
  color: #333;
  /* padding: 20px; */
  font-family: "Helvetica Neue", Arial, sans-serif;
}

.order-container {
  max-width: 1200px;
  margin: 0 auto;
  gap: 15px; /* 减少容器内部间距 */
}

.main-content {
  display: flex;
  gap: 15px; /* 减少主内容区域间距 */
}

.left-column {
  flex: 7;
  display: flex;
  flex-direction: column;
  gap: 15px; /* 减少左侧列间距 */
}

.right-column {
  flex: 3;
}

.section-card {
  border-radius: 4px;
  overflow: hidden;
}

.card-header {
  background-color: #f5f7fa;
  padding: 15px 20px;
  border-bottom: 1px solid #e6e6e6;
}

.card-body {
  padding: 20px;
  background-color: #fff;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.address-item {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 10px; /* 减少地址项内边距 */
  display: flex;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #409eff;
}

.address-item.active {
  border-color: #ff9900;
  box-shadow: 0 0 5px rgba(255, 153, 0, 0.3);
}

.address-icon {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  flex-shrink: 0;
}

.address-content {
  flex: 1;
}

.address-text {
  font-size: 14px;
  margin-bottom: 5px;
  line-height: 1.4;
}

.contact-info {
  font-size: 13px;
  color: #666;
}

.toggle-address-btn {
  margin-top: 15px;
}

.product-details {
  display: flex;
  margin-bottom: 15px; /* 减少产品详情底部间距 */
  padding-bottom: 15px; /* 减少产品详情底部内边距 */
  border-bottom: 1px solid #eee;
}

.product-image {
  width: 80px; /* 减小图片宽度 */
  height: 80px; /* 减小图片高度 */
  margin-right: 10px; /* 减少图片与文字间距 */
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 10px;
}

.product-price {
  color: #ff3c00;
  font-size: 18px;
  font-weight: 600;
}

.product-description {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.section-title {
  font-weight: 600;
  margin-bottom: 10px;
  font-size: 14px;
}

.size-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.size-option {
  padding: 5px 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
}

.size-option:hover {
  border-color: #409eff;
}

.size-option.active {
  background-color: #ff9900;
  border-color: #ff9900;
  color: white;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 30px;
  height: 30px;
  padding: 0;
}

.quantity {
  margin: 0 15px;
  font-weight: 500;
}

.address-info p,
.order-info p {
  margin: 10px 0;
  color: #606266;
}

.order-items {
  margin-top: 15px;
}

.order-item {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

.price-row {
  display: flex;
  justify-content: space-between;
  margin: 10px 0; /* 减少价格行间距 */
}

.total-row {
  border-top: 1px solid #ebeef5;
  padding-top: 10px; /* 减少总金额顶部内边距 */
  font-weight: bold;
  font-size: 16px;
}

.total-price {
  color: #ff3c00;
  font-size: 18px;
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }

  .address-list {
    grid-template-columns: 1fr;
  }

  .product-details {
    flex-direction: column;
  }

  .product-image {
    width: 100%;
    height: 150px; /* 调整移动端图片高度 */
    margin-right: 0;
    margin-bottom: 10px; /* 减少移动端图片与文字间距 */
  }
}
</style>
